/***************************************************************************
 *   Copyright (C) 2008 by Tomasz Dubik                                    *
 *   tdubik@gmail.com                                                      *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/

#include "task.h"
#include <cassert>
#include <QDebug>

namespace Tasks
{

    static const char* KTimeFormat = "%Y-%m-%d.%H:%M:%S";
    static const char* KSTimeFormat = "%d-%d-%d.%d:%d:%d";

    Task::Task(Task* parent):m_pParent(parent)
    {

    };

    Task::Task(const Task& task)
    {
        for(int i = 0; i< task.childCount(); ++i)
            addTask(*task.child(i));
            
        m_Text = task.text();
        m_pParent = task.parent();
        m_Progress= task.progress();
        m_ID = task.id();
        m_LastModify = task.lastModify();
    }

    Task::~Task()
    {        
        deleteChilds();
    }

    int Task::childCount()const
    {
        return m_Childs.size();
    }

    Task* Task::child(int ind) const
    {
        if( (int)m_Childs.size() > ind)
            return m_Childs[ind];
        else
            return NULL;
    }

    void Task::addTask(Task& newTask)
    {
        qDebug() << Q_FUNC_INFO << "selfID: "<< m_ID;
        Task* myNewTask = new Task(newTask);
        myNewTask->setParent(*this);
        m_Childs.push_back(myNewTask);
    }
    
    void Task::deleteChilds()
    {
        vector<Task*>::iterator it = m_Childs.begin();
        while( it != m_Childs.end())
        {
            delete *it;
            it++;
        }
        m_Childs.clear();    
    }
    
    void Task::removeChild(Task* task)
    {
        qDebug() << Q_FUNC_INFO;
        qDebug() << "child id: " << task->id();

        vector<Task*>::iterator it = m_Childs.begin();
        while( it != m_Childs.end())
        {
            if(*it == task )
            {
                cout << "task found +=erase it";
                m_Childs.erase(it);
                return;
            }
            ++it;
        }
    }

    void Task::setParent(Task& parent)
    {
        m_pParent = &parent;
    }
    
    Task* Task::find(UID ID)
    {       
        if( ID == m_ID )
            return this;
        else
        {
            vector<Task*>::iterator it;
            it = m_Childs.begin();
            Task* result = NULL;
            while( it != m_Childs.end() )
            {
                if( (result = (*it)->find( ID )) != NULL )
                    return result;
                ++it;
            }
        }
        return NULL;
    }

    void Task::save(TiXmlElement* parent)
    {
        TiXmlElement* currentItem = new TiXmlElement("item");
        parent->LinkEndChild(currentItem);
        currentItem->SetAttribute("ID", m_ID);
        currentItem->SetAttribute("Text", m_Text.c_str());
        currentItem->SetAttribute("Progress", m_Progress);
        char* strTime = new char(50);
        timeToString(m_LastModify, strTime);
        currentItem->SetAttribute("LastModify", strTime);
        delete strTime;
        Task::Vector::iterator it = m_Childs.begin();
        while( it != m_Childs.end() )
        {
            (*it)->save(currentItem);
            ++it;
        }
    }

    Task::Task(TiXmlElement* item, Task* parent)
    {
        m_pParent = parent;
        item->Attribute("ID", &m_ID);
        qDebug() << "new Item ID " << m_ID;
        m_Text = item->Attribute("Text");
        qDebug() << "new item Txt: " << QString::fromStdString(m_Text);
        item->Attribute("Progress", &m_Progress);
        qDebug() << "new item Progress: " << m_Progress;
        string tempTime = item->Attribute("LastModify");
        m_LastModify = stringToTime(tempTime.c_str());
        TiXmlElement* childs = item->FirstChildElement();
        Task* newChilds = NULL;
        for(childs; childs; childs=childs->NextSiblingElement())
        {            
            qDebug() << "Parent ID: "<< m_ID;
            newChilds = new Task(childs);
            newChilds->setParent(*this);
            m_Childs.push_back(newChilds);
        }
    }

    void Task::calculateCurrentID(int& currentID)
    {
        if( currentID < m_ID )
            currentID = m_ID;

        Vector::iterator it = m_Childs.begin();
        while( it != m_Childs.end() )
        {
            (*it)->calculateCurrentID( currentID );
            ++it;
        }
    }

    void Task::timeToString(time_t time, char*& result)
    {        
        strftime(result, 50, KTimeFormat, localtime(&time));
    }

    time_t Task::stringToTime(const char* strTime)
    {
        tm timeDate;
        int year = 0, mon = 0;
        sscanf(strTime,KSTimeFormat, &year, &mon, &timeDate.tm_mday, &timeDate.tm_hour, &timeDate.tm_min, &timeDate.tm_sec);
        timeDate.tm_year = year - 1900;
        timeDate.tm_mon = mon - 1;
        time_t newTime = mktime(&timeDate);
        return newTime;
    }
}
//eof
